package com.liuyi.framework.upload;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.ArrayUtil;
import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.StrUtil;
import com.liuyi.tools.web.unusual.HttpStatusBizException;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;

/**
 * @author Mr.fmy
 * @version 1.0.0
 * @ClassName UploadTool
 * @Description TODO Spring上传工具类
 * @createTime 2020/4/8 09:10
 */
@Slf4j
public class SpringUploadTool {

    /**
     * 获取文件真实后辍
     */
    private static String fileAfterName(MultipartFile file) {
        String[] strings = StrUtil.split(file.getOriginalFilename(), ".");
        return strings[(strings.length - 1)];
    }

    /**
     * Spring 上传方法
     *
     * @param multipartFile 文件
     * @param uploadEnum    上传类型
     * @return 上传文件地址
     */
    public static String upload(MultipartFile multipartFile, UploadEnum uploadEnum) {
        if (uploadEnum == null || multipartFile == null || multipartFile.isEmpty()) {
            throw new HttpStatusBizException("请上传文件");
        }
        try {
            String fileType = fileAfterName(multipartFile);
            if (!uploadEnum.getTypes().contains(fileType)) {
                throw new HttpStatusBizException("上传类型错误，目前支持类型：{0}", ArrayUtil.wrap(CollUtil.join(uploadEnum.getTypes(), ",")));
            }
            String path = uploadEnum.getPath() + File.separator + uploadEnum.getFolder(); //这个不用带文件名
            String fileName = IdUtil.simpleUUID() + "." + fileType;
            String result = uploadEnum.getResult() + fileName;
            File file = new File(path, fileName);
            FileUtil.touch(file);
            multipartFile.transferTo(file);
            return result;
        } catch (IOException e) {
            log.error(uploadEnum.toString(), e);
            throw new HttpStatusBizException("上次失败");
        }
    }
}
